package broker

import (
	"context"
	"fmt"
	"manager/bll"
	log "manager/collector/logger"
	"manager/event"
	"manager/lib/trace_log"
	"manager/store/redis"
	"manager/utils"
	"strings"
	"time"
)

var DeviceStatus = &deviceStatus{}

// DeviceStatus 设备状态
type deviceStatus struct {
}

func (d *deviceStatus) init() func() {
	return func() {}
}

func (d *deviceStatus) onEvent(data *event.Data) {
	if data == nil || (data.Type != event.Event_Power_On && data.Type != event.Event_Power_Off && data.Type != event.Event_Power_On_Cmd) {
		return
	}
	log.Info("---------------- deviceCyclingReport onEvent data:", utils.ToJsonString(data))

	// 一键启动命令
	if data.Type == event.Event_Power_On_Cmd {
		// 解析参数
		obj := data.Data.(*event.BikePowerOnCmd)
		if obj == nil {
			log.Error("deviceStatus BikePowerOnCmd onEvent err")
			return
		}

		// 添加一键启动
		key := fmt.Sprintf("%v", obj.BikeId)
		value := fmt.Sprintf("%v_%v", obj.UserId, "off")
		if err := redis.KV.AddValueWithExpireTime(context.Background(), DevicePowerOnStatusKey, key, fmt.Sprintf("%v", value), time.Second*60); err != nil {
			log.Errorf("deviceStatus AddValueWithExpireTime err:%v", err)
		}

		return
	}

	// 上电
	if data.Type == event.Event_Power_On {
		// 解析参数
		obj := data.Data.(*event.BikePowerOn)
		if obj == nil {
			log.Error("deviceStatus onEvent err")
			return
		}

		// 车辆下电
		bikeInfo, _ := bll.CacheBike.GetBikeInfoById(obj.EbikeId)
		if bikeInfo != nil && bikeInfo.SNCode != "" {
			trace_log.DebugLogger(bikeInfo.SNCode, "broker deviceStatus Event_Power_On onEvent", "上电")
		}

		key := fmt.Sprintf("%v", obj.EbikeId)

		info, _ := bll.CacheBike.GetBikeInfoById(obj.EbikeId)
		if info != nil {
			trace_log.DebugLogger(info.SNCode, "---------- 车辆上电 ------------ ")
		}

		var value string
		redis.KV.GetValue(context.Background(), DevicePowerOnStatusKey, key, &value)
		if value != "" {
			rets := strings.Split(value, "_")
			if len(rets) == 0 || rets[0] == "" {
				log.Errorf("deviceStatus Event_Power_On one button start failed")
				return
			}
			value = fmt.Sprintf("%v_%v", rets[0], "on")
			if err := redis.KV.AddValueWithExpireTime(context.Background(), DevicePowerOnStatusKey, key, value, time.Second*60); err != nil {
				log.Errorf("deviceStatus AddValueWithExpireTime err:%v", err)
			}
			return
		} else {
			managerId := bll.UserEbike.GetManagerByBikeId(obj.EbikeId)
			trace_log.ErrorLogger.Error("deviceStatus Event_Power_On 车辆上电 managerId", managerId)
			if managerId > 0 {
				value = fmt.Sprintf("%v_%v", managerId, "on")
				if err := redis.KV.AddValueWithExpireTime(context.Background(), DevicePowerOnStatusKey, key, value, time.Second*60); err != nil {
					log.Errorf("deviceStatus AddValueWithExpireTime err:%v", err)
				}
				return
			}
		}

		trace_log.ErrorLogger.Error("deviceStatus Event_Power_On exception", "bikeId", obj.EbikeId)
		return
	}

	// 下电
	if data.Type == event.Event_Power_Off {
		// 解析参数
		obj := data.Data.(*event.BikePowerOff)
		if obj == nil {
			log.Error("deviceStatus onEvent err")
			return
		}

		managerId := bll.UserEbike.GetManagerByBikeId(obj.EbikeId)
		trace_log.ErrorLogger.Error("deviceStatus Event_Power_Off 车辆下电 managerId", managerId)

		info, _ := bll.CacheBike.GetBikeInfoById(obj.EbikeId)
		if info != nil {
			trace_log.DebugLogger(info.SNCode, "---------- 车辆下电 ------------ ")
		}
		return
	}
}

// IsPowerOn 是否一键启动成功
func (d *deviceStatus) IsPowerOn(bikeId int64) bool {
	key := fmt.Sprintf("%v", bikeId)
	var value string
	redis.KV.GetValue(context.Background(), DevicePowerOnStatusKey, key, &value)
	rets := strings.Split(value, "_")
	if len(rets) != 2 {
		return false
	}
	if len(rets) == 0 {
		log.Errorf("deviceStatus IsPowerOn one button start failed")
		return false
	}

	return rets[1] == "on"
}

// IsPowering 是否正在一键启动
func (d *deviceStatus) IsPowering(bikeId int64) bool {
	key := fmt.Sprintf("%v", bikeId)
	var value string
	redis.KV.GetValue(context.Background(), DevicePowerOnStatusKey, key, &value)
	rets := strings.Split(value, "_")
	if len(rets) != 2 {
		return false
	}

	if len(rets) == 0 {
		log.Errorf("deviceStatus IsPowerOn one button start failed")
		return false
	}

	return rets[1] == "off"
}

// GetPowerOnUser 获取开机用户
func (d *deviceStatus) GetPowerOnUser(bikeId int64) (bool, int64) {
	key := fmt.Sprintf("%v", bikeId)
	var value string
	redis.KV.GetValue(context.Background(), DevicePowerOnStatusKey, key, &value)
	rets := strings.Split(value, "_")
	if len(rets) != 2 {
		managerId := bll.UserEbike.GetManagerByBikeId(bikeId)
		return false, managerId
	}

	bikeInfo, _ := bll.CacheBike.GetBikeInfoById(bikeId)
	if bikeInfo != nil && bikeInfo.SNCode != "" {
		trace_log.DebugLogger(bikeInfo.SNCode, "GetPowerOnUser value:", value)
	}

	userId := utils.StrToInt64(rets[0])
	if userId == 0 {
		// 获取车主进行记录，进行容错
		userId = bll.UserEbike.GetManagerByBikeId(bikeId)
	}

	if len(rets) == 0 {
		log.Errorf("deviceStatus IsPowerOn one button start failed")
		return false, userId
	}

	return rets[1] == "on", userId

}
